package hy.sell;

import hy.pool.Util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.CountDownLatch;

public class TestApp {
    public static void main(String[] args) throws InterruptedException {
        JedisPool pool= Util.getInstance();
        Jedis j=pool.getResource();
        j.set("count","10");//一共10件商品
        j.ltrim("orders",-1,0);//清空订单的消息队列

        CountDownLatch cd=new CountDownLatch(100);//减法器，初始值为100，当其值为0时线程就不阻塞


        for(int i=0;i<100;i++){
            new Thread(i+"号"){
                public void run() {
                    Jedis j=null;
                    try{
                        j=pool.getResource();
                        long count=Long.valueOf(j.get("count"));
                        if(count<=0){
                            System.out.println("没商品了，直接退出!");
                            return;
                        }
                        count=j.decr("count");
                        if(count>=0){
                            j.rpush("orders",Thread.currentThread().getName());
                        }else{
                            System.out.println("xxxxxxxxxxxxxxx虽然成功减了库存，但你还是买不到!xxxxxxxxxxxxxxxxxxxx");
                        }
                    }finally {
                        Util.release(pool,j);
                        cd.countDown();
                    }
                }
            }.start();
        }

        cd.await();
        System.out.println("==================="+j.lrange("orders",0,-1)+"====================");
        Util.release(pool,j);
    }
}
